package com.self.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.self.member.constant.MemberConstant;
import com.self.member.mapper.UserBankMapper;
import com.self.member.model.User;
import com.self.member.model.UserBank;
import com.self.member.service.UserBankService;
import com.self.member.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.Assert;

@Service
public class UserBankServiceImpl extends ServiceImpl<UserBankMapper, UserBank> implements UserBankService {

    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Page<UserBank> findByPage(Page<UserBank> page, Long usrId) {
        return page(page,new LambdaQueryWrapper<UserBank>().eq(usrId != null,UserBank::getUserId,usrId));
    }

    @Override
    public UserBank getUserBankByUserId(Long userId) {
        UserBank userBank = getOne(
                new LambdaQueryWrapper<UserBank>()
                        .eq(UserBank::getUserId, userId)
                        .eq(UserBank::getStatus, MemberConstant.STATUS_ENABLE));
        return userBank;
    }

    @Override
    public boolean bindBank(Long userId, UserBank userBank) {
        //支付密码校验
        String payPassword = userBank.getPayPassword();
        User user = userService.getById(userId);
        Assert.notNull(user,"当前用户信息不存在");
        boolean matches = passwordEncoder.matches(payPassword, user.getPaypassword());
        Assert.isTrue(matches,"支付密码不正确");
        Long id = userBank.getId();
        if (id != null){
            UserBank bank = getById(id);
            Assert.notNull(bank,"银行卡不存在");
            return updateById(userBank);
        }
        userBank.setUserId(userId);
        return save(userBank);
    }


}
